<template>

  <a-select
    v-if="async"
    showSearch
    labelInValue
    :disabled="disabled"
    :getPopupContainer="getParentContainer"
    @search="loadData"
    :placeholder="placeholder"
    v-model="selectedAsyncValue"
    style="width: 100%"
    :filterOption="false"
    @change="handleAsyncChange"
    allowClear
    :notFoundContent="loading ? undefined : null"
  >
    <a-spin v-if="loading" slot="notFoundContent" size="small"/>
    <a-select-option v-for="d in options" :key="d.value" :value="d.value">{{ d.text }}</a-select-option>
  </a-select>

  <a-select
    v-else
    :getPopupContainer="getParentContainer"
    showSearch
    :disabled="disabled"
    :placeholder="placeholder"
    optionFilterProp="children"
    style="width: 100%"
    @change="handleChange"
    :filterOption="filterOption"
    v-model="selectedValue"
    allowClear
    :notFoundContent="loading ? undefined : null">
    <a-spin v-if="loading" slot="notFoundContent" size="small"/>
    <a-select-option v-for="d in options" :key="d.value" :value="d.value">{{ d.text }}</a-select-option>
  </a-select>

</template>

<script>
  import { ajaxGetDictItems,getDictItemsFromCache } from '@/api/api'
  import debounce from 'lodash/debounce';
  import { getAction } from '../../api/manage'

  export default {
    name: 'JSearchSelectTag',
    props:{
      dictCode: String,
      mainId: String,
      initId: String,
      disabled: Boolean,
      value: [String, Number],
      dict: String,
      dictWhere:{
        type:String,
        required:false,
        default:"",
      },
      dictOptions: Array,
      async: Boolean,
      placeholder:{
        type:String,
        default:"请选择",
        required:false
      },
      popContainer:{
        type:String,
        default:'',
        required:false
      },
      pageSize:{
        type: Number,
        default: 10,
        required: false
      },
      getPopupContainer: {
        type:Function,
        default: null
      },
    },
    data(){
      this.loadData = debounce(this.loadData, 800);//消抖
      this.lastLoad = 0;
      return {
        loading:false,
        selectedValue:[],
        selectedAsyncValue:[],
        options: [],
        url:'/yw/api/data/',
      }
    },
    // created(){
    //   setTimeout(() =>{
    //     console.log(this.mainId)
    //     this.initDictData();
    //   }, 5000)
    // },
    watch:{
      "value":{
        immediate:true,
        handler(val){
          if(!val){
            if(val==0){
              this.initSelectValue()
            }else{
              this.selectedValue=[]
              this.selectedAsyncValue=[]
            }
          }else{
            this.initSelectValue()
          }
        }
      },
      // "dict":{
      //   handler(){
      //     console.log('22222222222222')
      //     this.initDictData()
      //   }
      // },
      // dictWhere:{
      //   deep:true,
      //   immediate:true,
      //   handler(){
      //     console.log('33333333333333')
      //     this.initDictData()
      //   }
      // },
      'dictOptions':{
        deep: true,
        handler(val){
          if(val && val.length>0){
            this.options = [...val]
          }
        }
      },
      // dictCode:{
      //   immediate:true,
      //   handler(n) {
      //     console.log('4444444444444')
      //     this.initDictData();
      //   },
      // },
      mainId:{
        deep:true,
        immediate:true,
        handler(n) {
          if(n){
            //console.log('555555555555')
            this.initDictData();
          }

        },
      },
      initId:{
        deep:true,
        immediate:true,
        handler(n) {
          if(n){
            //console.log('666666666666666666')
            this.initDictData();
          }
        },
      },
    },
    methods:{
      initSelectValue(){
        this.selectedValue = this.value.toString()
        this.callback()
      },
      loadData(value){
        //console.log("数据加载",value)
        // this.lastLoad +=1
        // const currentLoad = this.lastLoad
        // this.options = []
        // this.loading=true
        // // 字典code格式：table,text,code
        // getAction(`/sys/dict/loadDict/${this.dict}`,{keyword:value, pageSize: this.pageSize,dictWhere:this.dictWhere}).then(res=>{
        //   this.loading=false
        //   if(res.success){
        //     if(currentLoad!=this.lastLoad){
        //       return
        //     }
        //     this.options = res.result
        //     //console.log("我是第一个",res)
        //   }else{
        //     this.$message.warning(res.message)
        //   }
        //
        // })

      },
      initDictData(){
          //如果字典项集合有数据
          if(this.dictOptions && this.dictOptions.length>0){
            this.options = [...this.dictOptions]
          }else{
            if(this.dictCode){
              console.log({id:this.mainId,initId:this.initId})
              if(this.mainId || this.initId){
                getAction(this.url+this.dictCode,{id:this.mainId,initId:this.initId}).then(res=>{
                  if(res.success){
                    this.options = res.result;
                  }else{
                    this.$message.warning(res.message)
                  }
                })
              }
            }
          }

      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      handleChange (selectedValue) {
        //console.log("selectedValue",selectedValue)
        this.selectedValue = selectedValue
        this.callback()
      },
      handleAsyncChange(selectedObj){
        //update-begin-author:scott date:20201222 for:【搜索】搜索查询组件，删除条件，默认下拉还是上次的缓存数据，不好 JT-191
        if(selectedObj){
          this.selectedAsyncValue = selectedObj
          this.selectedValue = selectedObj.key
        }else{
          this.selectedAsyncValue = null
          this.selectedValue = null
          this.options = null
          this.loadData("")
        }
        this.callback()
        //update-end-author:scott date:20201222 for:【搜索】搜索查询组件，删除条件，默认下拉还是上次的缓存数据，不好 JT-191
      },
      callback(){
        //console.log(this.selectedValue)
        this.$emit('change', this.selectedValue);
      },
      setCurrentDictOptions(dictOptions){
        this.options = dictOptions
      },
      getCurrentDictOptions(){
        return this.options
      },
      getParentContainer(node){
        if(typeof this.getPopupContainer === 'function'){
          return this.getPopupContainer(node)
        } else if(!this.popContainer){
          return node.parentNode
        }else{
          return document.querySelector(this.popContainer)
        }
      },

    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>

</style>